package cn.jimmie.lib.qlog.support;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import cn.jimmie.lib.qlog.QLog;

/**
 * Created by <zhangsheng@4399inc.com> on 2018-06-06.
 */
public final class AlApp {
    public static String getVersion(Context ctx) {
        try {
            PackageInfo pi = getPackageInfo(ctx);
            if (pi != null)
                return pi.versionName;
        } catch (Exception e) {
            QLog.e("Get app version failed: %s", e.getMessage());
        }
        return "";
    }

    public static int getVersionCode(Context ctx) {
        try {
            PackageInfo pi = getPackageInfo(ctx);
            if (pi != null)
                return pi.versionCode;
        } catch (Exception e) {
            QLog.e("Get app version failed: %s", e.getMessage());
        }
        return 0;
    }

    private static PackageInfo getPackageInfo(Context ctx) {
        try {
            return ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            QLog.e("Package with given name not found: %s", e.getMessage());
            return null;
        }
    }
}
